package com.jjyu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jjyu.dao.FeedbackMapper;
import com.jjyu.entity.Feedback;
import com.jjyu.service.FeedbackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class FeedbackServiceImpl extends ServiceImpl<FeedbackMapper, Feedback> implements FeedbackService {

    @Autowired
    private FeedbackMapper feedbackMapper;

    // 提交用户反馈
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Feedback submitFeedback(Feedback feedback) {
        if (feedback.getRating() < 1 || feedback.getRating() > 5) {
            throw new IllegalArgumentException("Rating must be between 1 and 5");
        }
        feedback.setCreatedAt(LocalDateTime.now());
        feedback.setUpdatedAt(LocalDateTime.now());
        feedbackMapper.insert(feedback);
        return feedback;
    }

    // 获取所有反馈
    @Override
    public List<Feedback> getAllFeedbacks() {
        return feedbackMapper.selectList(null); // 使用MyBatis-Plus的selectList方法获取所有记录
    }

    // 根据用户ID获取反馈
    @Override
    public List<Feedback> getFeedbacksByUserId(Integer userId) {
        return feedbackMapper.selectList(new QueryWrapper<Feedback>().eq("user_id", userId));
    }

    // 根据推荐内容ID获取反馈
    @Override
    public List<Feedback> getFeedbacksByRecommendationId(Integer recommendationId) {
        return feedbackMapper.selectList(new QueryWrapper<Feedback>().eq("recommendation_id", recommendationId));
    }

    // 更新反馈
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Feedback updateFeedback(Long id, Feedback feedback) {
        Feedback existingFeedback = feedbackMapper.selectById(id);
        if (existingFeedback == null) {
            throw new IllegalArgumentException("Feedback not found with ID: " + id);
        }

        if (feedback.getRating() != null) {
            existingFeedback.setRating(feedback.getRating());
        }
        if (feedback.getComment() != null) {
            existingFeedback.setComment(feedback.getComment());
        }
        existingFeedback.setUpdatedAt(LocalDateTime.now());

        feedbackMapper.updateById(existingFeedback);
        return existingFeedback;
    }
}